package com.promise.jokerdream.work.signup

import com.promise.jokerdream.database.entity.AscendHeavenGameConfigEntity
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.utils.TimeUtils
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import java.util.Calendar

// 飞升大作战工作
class AscendHeavenWork(
    private val config: AscendHeavenGameConfigEntity,
    uin: String
): BaseWork(uin) {

    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }

    override val name: String
        get() = "飞升"

    override suspend fun executeWork(): WorkResult {
        return try {
            // 检查报名时间：13:00-22:00
            val currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
            if (currentHour < 13 || currentHour >= 22) {
                return WorkResult.Success
            }
            
            
            // 查询飞升大作战状态
            val queryResult = gameApi.queryAscendHeaven()
            
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    // 检查是否已报名（signStatus为0表示未报名）
                    if (response.signStatus == 0) {
                        // 未报名，执行报名
                        val gameMode = try { com.promise.jokerdream.config.game.AscendHeavenGameMode.valueOf(config.gameMode) } catch (e: Exception) { com.promise.jokerdream.config.game.AscendHeavenGameMode.MATCH }
                        val signupResult = gameApi.ascendHeavenSignup(gameMode.signupType)
                        signupResult.foldWithApiException(
                            onSuccess = { signupResponse ->
                                historyManager.addHistory(name, signupResponse.getDescription())
                                WorkResult.Success
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                                WorkResult.Failure(Exception(msg), msg)
                            }
                        )
                    } else {
                        WorkResult.Success
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
    
}